package cn.yusei.teamTribe.controller.team;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.constant.RoleType;
import cn.yusei.teamTribe.service.team.TeamRoleService;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class TeamRoleController {

	@Autowired
	private TeamRoleService teamRoleService;
	
	@RequestMapping(value="/teamRole/add")
	public void add(@RequestAttribute int id, @RequestParam int teamId, @RequestParam int roleId, @RequestParam int userId, PrintWriter out)
	{
		if(teamId <= 0 || userId <= 0)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code = 0;
		try
		{
			code = teamRoleService.add(id, teamId, roleId, userId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
	@RequestMapping(value="/teamRole/get")
	public void get(@RequestParam int teamId, @RequestParam int roleId, PrintWriter out)
	{
		if(teamId <= 0 || !RoleType.isRoleType(roleId))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int[] ids = null;
		try
		{
			ids = teamRoleService.get(teamId, roleId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", ids);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
	
	@RequestMapping(value="/teamRole/delete")
	public void delete(@RequestAttribute int id,
			@RequestParam int userId, @RequestParam int teamId, @RequestParam int roleId, PrintWriter out)
	{
		if(userId <= 0 || teamId <= 0 || RoleType.isRoleType(roleId))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code = 0;
		try
		{
			code = teamRoleService.delete(id, teamId, roleId, userId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
}
